package com.aurora.leetcode.answer;

import com.aurora.leetcode.entity.ListNode;
import com.aurora.leetcode.util.MyUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : Aurora
 * @date : 2024/4/24 10:37
 * @description
 * <title>给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。</title>
 * <p>输入：head = [1,2,3,4,5], n = 2</p>
 * <p>输出：[1,2,3,5]</p>
 */
public class RemoveNthFromEnd_19 {
    List<ListNode> position = new ArrayList<>();
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(n <= 0)return head;
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode p = dummy;
        while(p.next != null){
            position.add(p.next);
            p = p.next;
        }
        int size = position.size();
        ListNode pre = new ListNode();
        if(n < size){
            pre = position.get(size-n-1);
        } else if (n ==size){
            pre = dummy;
        }else{
            return head;
        }
        ListNode del = position.get(size-n);
        pre.next = del.next;
        return dummy.next;
    }

    public static void main(String[] args) {
        RemoveNthFromEnd_19 obj = new RemoveNthFromEnd_19();
        int[] arr = new int[]{1,2,3,4,5};
        ListNode listNode = MyUtils.constructListNode(arr);
        System.out.println("删除元素之前：");
        MyUtils.printLinkedList(listNode);
        System.out.println("删除元素之后：");
        MyUtils.printLinkedList(obj.removeNthFromEnd(listNode,0));
    }
}
